package com.ncdnapp.util;

import org.noear.solon.Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: chenbin
 * @Description:
 * @Date: create in 2022/4/11 11:07
 */
public class ThreadLocalDataHelper {
    private static final ThreadLocal<Map<String, Object>> localData = new ThreadLocal<>();

    /**
     * 设置
     *
     * @param dataMap 数据集合
     */
    public static void setData(Map<String, Object> dataMap) {
        localData.set(dataMap);
    }

    public static void setData(String name, Object value) {
        Map<String, Object> dataMap = getData();
        if (dataMap == null) {
            dataMap = new HashMap<>();
            localData.set(dataMap);
        }
        dataMap.put(name, value);
    }

    /**
     * 获取请求参数
     *
     * @param param key
     * @return 数据
     */
    public static Object getData(String param) {
        Map<String, Object> dataMap = getData();
        if (!Utils.isEmpty(dataMap)) {
            return dataMap.get(param);
        }
        return null;
    }

    /**
     * 获取
     *
     * @return 全部数据
     */
    public static Map<String, Object> getData() {
        return localData.get();
    }

    public static boolean contains(String param) {
        Map<String, Object> dataMap = getData();
        if (!Utils.isEmpty(dataMap)) {
            return dataMap.containsKey(param);
        }
        return false;
    }

    public static void remove(String param) {
        Map<String, Object> dataMap = getData();
        if (!Utils.isEmpty(dataMap)) {
            dataMap.remove(param);
        }
    }

    public static void clear() {
        Map<String, Object> dataMap = getData();
        if (!Utils.isEmpty(dataMap)) {
            dataMap.clear();
        }
    }
}
